package humrum.weguide.net;

/*
 * Copyright (C) Weguide
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * 
 * @author aderbal
 */

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;

public class Request {
	
	private String _responseData;
	private JSONArray _jsonArray;
	
	private HttpClient client;
	private HttpPost post;
	private HttpResponse response;
	private HttpEntity entity;
	private BufferedReader bfread;
	private StringBuilder sb;
	
	/**
	 * Get URL data content
	 * 
	 * @param String url
	 * @return JSONArray - null of erros
	 */
	public JSONArray getData(String url){
		InputStream is = null;
		try{
			// get data from url
			client = new DefaultHttpClient();
			post = new HttpPost(url);
			response = client.execute(post);
			entity = response.getEntity();
			is = entity.getContent();
		}catch(Exception e){
			e.printStackTrace();
			return null;
		}
		// convert data to String
		try{
			bfread = new BufferedReader(new InputStreamReader(is, "UTF-8"), 8);
			sb = new StringBuilder();
			String line = null;
			while((line = bfread.readLine()) != null){
				sb.append(line);
			}
			is.close();
			is = null;
			// result final
			_responseData = sb.toString();
		}catch(Exception ex){
			ex.printStackTrace();
		}
		// decode string data
		return decode(_responseData);
	}

	/**
	 * Decode string json format to JSONArray
	 * 
	 * @param String json
	 * @return JSONArray - null if erros
	 */
	public JSONArray decode(String json){
		try{
			_jsonArray = new JSONArray(json);
		}catch(Exception e){
			e.printStackTrace();
			return null;
		}
		return _jsonArray;
	}
	
	/**
	 * Clean all unsed objects
	 * 
	 * @autor aderbal
	 */
	public void finish(){
		try {
			bfread.close();
			_jsonArray = null;
			client = null;
			post = null;
		} catch (IOException e) { }
	}
}
